package login;

import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import notification.LogNotifModel;
import notification.NotifManager;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.PathAttribute;

import Candidate.CandidateForm;
import Eclass.EclassForm;
import Eclass.EclassManager;
import Eclass.Exam.ExamManager;
import Eclass.Schedule.ScheduleForm;
import Eclass.Score.ScoreForm;
import Forum.ForumThreadForm;
import Master.SchoolForm;

import com.crystaldecisions.proxy.remoteagent.l;
import com.crystaldecisions.sdk.occa.report.formatteddefinition.model.Page;
import com.seagatesoftware.img.OCA.OCAs.Session;

public class LoginAction extends Action {
	
	private LoginManager manager = new LoginManager();	
	private ActiveDirectoryManager adm = new ActiveDirectoryManager();
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		HttpSession session = request.getSession(true);
		LoginForm logForm = (LoginForm) form;		
		UserModel userModel;
		NotifManager notifMgr;
		
//-------------------------------------------------------------- Navigation ----------------------------------------------------------
		CandidateForm candidateForm = new CandidateForm();
		SchoolForm schoolForm = new SchoolForm();
		EclassForm eClassForm = new EclassForm();
		ForumThreadForm forumForm = new ForumThreadForm();
		ScoreForm scoreForm = new ScoreForm();
		ScheduleForm scheduleForm = new ScheduleForm();
		
		if("updateCandidate".equalsIgnoreCase(logForm.getTask())) {
			//candidateForm.getcModel().setRegisNo("01-13-12- 029");
			//candidateForm.setTask("updateCandidateData");
			return mapping.findForward("candidate");
		}else if("manageTrainee".equalsIgnoreCase(logForm.getTask())) {	
			candidateForm.setTask("manageTrainee");
			return mapping.findForward("candidate");
		}else if("batch".equalsIgnoreCase(logForm.getTask())) {
			eClassForm.setTask("batch");
			return mapping.findForward("eclass");
		}else if("listExamPrep".equalsIgnoreCase(logForm.getTask())) {
			eClassForm.setTask("listExamPrep");
			return mapping.findForward("eclass");
		}else if("manageSchool".equalsIgnoreCase(logForm.getTask())) {
			schoolForm.setTask("manageSchool");
			return mapping.findForward("master");
  		}else if("forumPage".equalsIgnoreCase(logForm.getTask())) {
			forumForm.setTask("forumPage");
			return mapping.findForward("forum");
		}else if("report".equalsIgnoreCase(logForm.getTask())) {
			scoreForm.setTask("report");
			return mapping.findForward("score");
		}else if("profileSetting".equalsIgnoreCase(logForm.getTask())) {//Profile setting candidate :: intan
			candidateForm.setTask("profileSetting");
			return mapping.findForward("candidate");
		}else if("accountSetting".equalsIgnoreCase(logForm.getTask())) {//Account setting candidate :: intan
			candidateForm.setTask("accountSetting");
			return mapping.findForward("candidate");
		} if("manageJob".equalsIgnoreCase(logForm.getTask())){
			schoolForm.setTask("manageJob");
			return mapping.findForward("master");
		}
//------------------------------------------------------------------------------------------------------------------------------

		
		if ("logincheck".equalsIgnoreCase(logForm.getTask())) {
			userModel = new UserModel();
			//get login user
			userModel = this.login(logForm.getUsername(), logForm.getPassword());
			
			//cek logged user by role
			if(userModel != null){				
				//set session
				session.setAttribute("userLogin", userModel);
				//session.setAttribute("result", "Welcome, " + userModel.getUserid());
				
				if("admin".equalsIgnoreCase(userModel.getRole())){						
					System.out.println("------ ADMIN -------");
					System.out.println("Return : " + mapping.findForward("manageUser"));
					//return mapping.findForward("manageUser");
				}else if("trainer".equalsIgnoreCase(userModel.getRole())){
					System.out.println("------ TRAINER -------");
					System.out.println("Return : " + mapping.findForward("listSchedule"));
					//return mapping.findForward("listSchedule");
				}else if("trainee".equalsIgnoreCase(userModel.getRole())){
					System.out.println("------ TRAINEE -------");
					System.out.println("Return : " + mapping.findForward("listSchedule"));
					//return mapping.findForward("listSchedule");
				}else if("candidate".equalsIgnoreCase(userModel.getRole())){
					System.out.println("------ CANDIDATE -------");
					//return mapping.findForward("manageCandidate");
				}
				
				System.out.println("Return : " + mapping.findForward("welcome"));
				return mapping.findForward("welcome");
			}else{ //login failed
				System.out.println("-------- LOGIN FAILED -----------");
				session.setAttribute("result", "Login failed. Please check your username / password!");
				return mapping.findForward("login");
			}				
		}else if ("showNotif".equalsIgnoreCase(logForm.getTask())) {
			try{
				notifMgr = new NotifManager();
				userModel = (UserModel)session.getAttribute("userLogin");			
				logForm.setListNotif(notifMgr.getNotifications(userModel.getUserid()));
				//notifMgr.updateNotificationRead(userModel.getUserid());
				return mapping.findForward("showNotification");
			}catch(Exception ex){
				return mapping.findForward("login");
			}
		}
		else if ("goToNotifDest".equalsIgnoreCase(logForm.getTask())) {
			notifMgr = new NotifManager();
			LogNotifModel lnm = notifMgr.getLogNotifById(logForm.getModelLogNotif().getLogId());
			if(notifMgr.updateNotificationReadById(logForm.getModelLogNotif().getNotifId())){
				System.out.println("Success to Update Notification Read By user!");
			}
			else{
				System.out.println("Failed to Update Notification Read By user!");
			}
			String link = lnm.getLink();
			String isiTask = null;
			String isiGeneralId = null;
			
			try{
				if(link!=null){
					System.out.println("################ Link : "+link);
					isiTask = link.substring(link.indexOf("=")+1 ,link.indexOf("&"));
					isiGeneralId = link.substring(link.lastIndexOf("=")+1 ,link.length());
					
					System.out.println("*************&&&&&&&&&&&&& goToNotifDest isiTask : "+isiTask);
					System.out.println("*************&&&&&&&&&&&&& goToNotifDest isiGeneralId : "+isiGeneralId);
					System.out.println("###########test1");
					//utk notif Schedule
					if("showSchedule".equalsIgnoreCase(isiTask)){
						scheduleForm.setTask("listSchedule");
						scheduleForm.setSelectedBatchId(Integer.parseInt(isiGeneralId));
						session.setAttribute("showScheduleFromNotif", scheduleForm);
						System.out.println("***********showSchedule : Redirect to Schedule.do");
						return mapping.findForward("schedule");
					}
					else if("showThread".equalsIgnoreCase(isiTask)){
						forumForm.setTask("thread");
						forumForm.setIdThread(isiGeneralId);
						session.setAttribute("showThreadFromNotif", forumForm);
						System.out.println("***********showThread : Redirect to Forum.do");
						return mapping.findForward("forum");
					}
				}
			}
			catch(Exception ex){
				ex.printStackTrace();
				userModel = (UserModel)session.getAttribute("userLogin");	
				logForm.setListNotif(notifMgr.getNotifications(userModel.getUserid()));
				return mapping.findForward("showNotification");
			}
		}
		
		if(session != null){
			//destroy session if login page active
			if(session.getAttribute("userLogin") != null){
				userModel = (UserModel)session.getAttribute("userLogin");	
				userModel = logout(userModel);
				//destroy session
				session.invalidate();			
			}
		}
		
		System.out.println("Return : " + mapping.findForward("login"));
		return mapping.findForward("login");
		//return null;
	}
	
	public UserModel login(String username, String password){
		//adm.isAuthenticated(username, password);
		
		// encrypt password -- fanny
//		EclassManager eMan = new EclassManager();
//		try {
//			password = eMan.sha1(password);
//			
//			System.out.println("cek password : " + password);
//		} catch (NoSuchAlgorithmException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		String status = "";
		UserModel userModel = null;
		//System.out.println("/n/n----------------------/n/n");
		
		//get User from old database
		List listOldUser = manager.selectOldUser(username, "1", "0");		
		
		//check if user available
		if(listOldUser.size() > 0){
			//System.out.println("listOldUser : " + listOldUser.size());
			userModel = (UserModel)listOldUser.get(0);
			status = "old";
		}else{ 
			//user unavailable in old database
			List listNewUser = manager.selectNewUser(username, password, "1", "0");
			
			if(listNewUser.size() > 0){
				//System.out.println("listNewUser : " + listNewUser.size());
				userModel = (UserModel)listNewUser.get(0);
				status = "new";
			}
		}
		
		//update last login and login status
		if(userModel != null){
			if(userModel.getIsloggedin() != "1")
			{
				Date date = new Date();
				//System.out.println("== Date : " + date);
				userModel.setLastlogin(date);
				userModel.setIsloggedin("1");
				
				//update database
				if("old".equalsIgnoreCase(status)){
					userModel.setStatus("old");
					manager.UpdateOldUser(userModel);
				}else if("new".equalsIgnoreCase(status)){
					userModel.setStatus("new");
					manager.UpdateNewUser(userModel);
				}	
			}
		}
		
		return userModel;
	}
	
	public UserModel logout(UserModel user){
		UserModel userModel = user;
		boolean result = false;
		
		if(userModel != null){
			userModel.setIsloggedin("0");
			System.out.println("User DB : " + userModel.getStatus());
			//user on old database
			if("old".equalsIgnoreCase(userModel.getStatus())){
				result = manager.UpdateOldUser(userModel);
			}else{ //user on new database
				result = manager.UpdateNewUser(userModel);
			}
			System.out.println("Result Logout : " + result);
			if(result){
				userModel = null;
			}
		}
		
		return userModel;
	}
}
